package com.fingard.dsp.bank.helpers;

import com.fingard.FGBiz;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.helpers.dbhelpers.InsertHelper;
import com.fingard.dsp.bank.helpers.dbhelpers.LoadHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;

/**
 * 批次操作
 * <p>
 * ！！注意：需在finally里显示调用close()方法
 */
public class SeqRefundInfoHelper {

    private Connection partDbconn = null;

    /**
     * ！！注意：需在finally里显示调用close()方法
     *
     */
    public SeqRefundInfoHelper(String pTenant, Date pPartDate) throws Exception {
        partDbconn = FGBiz.partTable.getLoaclDbConnByPart(pTenant, pPartDate);
    }

    public void close() {
        if (partDbconn != null) {
            try {
                partDbconn.close();
            } catch (Exception ex) {
                FGBiz.limitMsg.exception("SeqRefundInfoHelper.closeLocalDbConn", ex);
            }
        }
    }

    /**
     * 按渠道分表，对应PartitionTable.initTableSeqRefundInfo
     */
    public static String getTableName(String pBankCode) {
        return "SEQREFUND" + pBankCode.toUpperCase();
    }

    /**
     * 将单笔信息写入数据库表
     */
    public boolean insertSeqRefundInfo(SeqRefundInfo pRefundInfo) throws Exception {
        String tabName = getTableName(pRefundInfo.bankCode);
        pRefundInfo.createdOn = new Date();
        pRefundInfo.lastModifiedOn = new Date();
        pRefundInfo.rowVersion = 0;
        int rowAff = InsertHelper.insertObject(partDbconn, tabName, pRefundInfo);
        if (rowAff == 1) {
            return true;
        } else {
            throw new Exception("写入" + tabName + "的影响行数：" + rowAff);
        }
    }

    public SeqRefundInfo loadFromDb(String pBankCode, String pReqSingNo) throws SQLException, IllegalArgumentException, IllegalAccessException, ParseException {
        String tabName = getTableName(pBankCode);
        String sql = "select * from " + tabName + " where ASKNUMBER=?";
        Object[] objs = new Object[1];
        objs[0] = pReqSingNo;
        Map<String, Object> mapData = JDBCHelper.execQuerySingle(partDbconn, sql, objs);
        if (mapData != null && mapData.size() > 0) {
            SeqRefundInfo pRefundInfo = new SeqRefundInfo();
            LoadHelper.loadObject(mapData, pRefundInfo);
            return pRefundInfo;
        }
        return null;
    }
}
